<template>
  <el-dialog
    :title="(action === 'add' ? '新增' : '修改') + '收货人地址'"
    width="40%" draggable :close-on-click-modal="false" v-model="visible" @open="submitted = false">
    <el-form
      :model="dataForm" :rules="dataRule" ref="dataFormRef"
      @keyup.enter="dataFormSubmit(dataFormRef)" label-width="100px">
      <el-form-item label="收货人名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="收货人名称" minlength="2" maxlength="10" show-word-limit />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="dataForm.phone" placeholder="联系电话" />
      </el-form-item>
      <el-form-item label="邮政编码" prop="postcode">
        <el-input v-model="dataForm.postcode" placeholder="邮政编码" maxlength="10" />
      </el-form-item>
      <el-form-item label="省份/直辖市" prop="province">
        <!-- TODO 优化成自动定位 -->
        <el-input v-model="dataForm.province" placeholder="省份/直辖市" maxlength="10" show-word-limit />
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <!-- TODO 优化成自动定位 -->
        <el-input v-model="dataForm.city" placeholder="城市" maxlength="10" show-word-limit />
      </el-form-item>
      <el-form-item label="区" prop="region">
        <!-- TODO 优化成自动定位 -->
        <el-input v-model="dataForm.region" placeholder="区" maxlength="10" show-word-limit />
      </el-form-item>
      <el-form-item label="详细地址" prop="detailAddress">
        <el-input v-model="dataForm.detailAddress" maxlength="50" placeholder="详细地址（街道、门牌号）" show-word-limit />
      </el-form-item>
      <el-form-item label="是否默认" prop="isDefault">
        <el-switch
          v-model="dataForm.isDefault"
          active-color="#13ce66" inactive-color="#ff4949"
          :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="ad-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit(dataFormRef)" :disabled="submitted">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import http from "@/utils/httpRequest";
import validate from "@/utils/validate";
import type { FormInstance } from "element-plus";
import { ref, reactive, nextTick, defineExpose, defineEmits } from "vue";


// 操作：add-新增，update-修改
const action = ref("");

// 弹窗是否显示
const visible = ref(false);

// 提交状态
const submitted = ref(false);

// 表单数据
const dataForm = reactive({
  id: undefined,
  name: "",
  phone: "",
  postcode: "",
  province: "",
  city: "",
  region: "",
  detailAddress: "",
  areacode: "", // TODO 没用上
  isDefault: 0,
});

// 数据校验规则
const dataRule = reactive({
  name: validate.required("收货人名称"),
  phone: validate.mobile(true),
  postcode: validate.required("邮政编码"),
  province: validate.required("省份/直辖市"),
  city: validate.required("城市"),
  region: validate.required("区"),
  detailAddress: validate.required("详细地址"),
});

// 表单引用
const dataFormRef = ref<FormInstance>();

// 父级组件的自定义事件
const emit = defineEmits(['updateReceiveAddressData']);

// 表单初始化
const initForm = async (a, id) => {
  action.value = a;
  // 新增操作
  if (a === "add") {
    visible.value = true;
    await nextTick();
    dataForm.id = '';
    dataFormRef.value.resetFields();
    return;
  }
  // 修改操作
  dataForm.id = id;
  http
    .post({
      url: `/member/receive-address/info?receiveAddressId=${dataForm.id}`,
    })
    .then(async ({ data }) => {
      if (http.success(data)) {
        visible.value = true;
        await nextTick();
        dataFormRef.value.resetFields();
        let form = data.body;
        Object.keys(form).forEach(function (key) {
          dataForm[key] = form[key];
        });
      }
    });
};

// 表单提交
const dataFormSubmit = (form: FormInstance | undefined) => {
  if (submitted.value) {
    return;
  }
  form.validate((valid) => {
    if (valid) {
      submitted.value = true;
      http
        .post({
          url: `/member/receive-address/save`,
          data: dataForm,
        })
        .then(({ data }) => {
          if (http.success(data, true)) {
            visible.value = false;
            emit("updateReceiveAddressData", data.body);
            return;
          }
          submitted.value = false;
        });
    }
  });
};

// 暴露方法
defineExpose({ initForm });
</script>
